<?php
namespace app\admin\controller;
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
header('Access-Control-Expose-Headers: *');  //服务器 headers 白名单，可以让客户端进行访问
header('Access-Control-Allow-Headers: *');
use app\BaseController;
use Cassandra\Future;
use League\Flysystem\Plugin\GetWithMetadata;
use think\facade\Db;
use think\model\concern\SoftDelete;
use think\response\Json;
use PHPMailer\PHPMailer\PHPMailer;

class Index extends BaseController
{
    public function email($len=6, $chars=null){
        $phone = input('phone');
        $mail = input('mail');
        if (is_null($chars)) {
            $chars = "0123456789";
        }
        mt_srand(10000000*(double)microtime());
        for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $lc)];
        }
        $toemail = $mail;//定义收件人的邮箱
        $mail = new PHPMailer();
        $mail->isSMTP();// 使用SMTP服务
        $mail->CharSet = "utf8";// 编码格式为utf8，不设置编码的话，中文会出现乱码
        $mail->Host = "smtp.qq.com";// 发送方的SMTP服务器地址
        $mail->SMTPAuth = true;// 是否使用身份验证
        $mail->Username = "2434730052@qq.com";// 发送方的163邮箱用户名，就是你申请163的SMTP服务使用的163邮箱</span><span style="color:#333333;">
        $mail->Password = "obnasaqarlcpdhib";// 发送方的邮箱密码，注意用163邮箱这里填写的是“客户端授权密码”而不是邮箱的登录密码！</span><span style="color:#333333;">
        $mail->SMTPSecure = "ssl";// 使用ssl协议方式</span><span style="color:#333333;">
        $mail->Port = 465;// 163邮箱的ssl协议方式端口号是465/994

        $mail->setFrom("2434730052@qq.com","阿源");// 设置发件人信息，如邮件格式说明中的发件人，这里会显示为Mailer(xxxx@163.com），Mailer是当做名字显示
        $mail->addAddress($toemail,$toemail);// 设置收件人信息，如邮件格式说明中的收件人，这里会显示为Liang(yyyy@163.com)
        $mail->addReplyTo("2434730052@qq.com","阿源");// 设置回复人信息，指的是收件人收到邮件后，如果要回复，回复邮件将发送到的邮箱地址
        //$mail->addCC("xxx@163.com");// 设置邮件抄送人，可以只写地址，上述的设置也可以只写地址(这个人也能收到邮件)
        //$mail->addBCC("xxx@163.com");// 设置秘密抄送人(这个人也能收到邮件)
        //$mail->addAttachment("bug0.jpg");// 添加附件
        $mail->Subject = "解放号";// 邮件标题
        $mail->Body = "您正在验证身份，验证码$str".PHP_EOL.'在10分钟内有效!'.PHP_EOL.'为了您的账号安全，请勿泄露给他人';// 邮件正文
//        $mail->Body = "您正在申请注册解放号，验证码为：$str".PHP_EOL.'在10分钟内有效!'.PHP_EOL.'如不是,请忽略!';// 邮件正文
        //$mail->AltBody = "This is the plain text纯文本";// 这个是设置纯文本方式显示的正文内容，如果不支持Html方式，就会用到这个，基本无用

        if(!$mail->send()){// 发送邮件
            echo "Message could not be sent.";
            echo "Mailer Error: ".$mail->ErrorInfo;// 输出错误信息
        }else{
            $timestamp = time();// -86400 秒数
            $date = strtotime("+10 minutes", $timestamp);
            $data = [
                'mailbox'=>$toemail,
                'verification'=>$str,
                'phone'=>$phone,
                'times'=>date('Y-m-d H:i:s',$date)
            ];
            $info = Db::name('mailbox')->where('mailbox',$data['mailbox'])->find();
            if (empty($info)){
                Db::name('mailbox')->insert($data);
            }else{
                foreach ($data as $v){
                    $data['id'] = $info['id'];
                }
                Db::name('mailbox')->update($data);
                $info = Db::name('mailbox')->where('phone',$phone)->find();
                return json($info);
            }
        }
    }
    public function index(){
        $type = input('type');
        if($type == 'cglb'){//主页 -- 采购列表
            $cglb=Db::name('bidding_hall')
                ->field('b.id,time,number,title,price,times,describe,cate,file,b.name,phone,c.name as catename,i.name as catenamepid')
                ->alias('b')
                ->join(['i_category' => 'c'], 'b.cate=c.id')
                ->join(['i_category' => 'i'], 'b.catepid=i.id')
                ->order('id desc')
                ->limit('10')
                ->where("b.state = 1")
                ->select();
            return Json($cglb);
        }
        if ($type == 'banner'){//首页 -- 图片
            $img = input('img');
            if ($img == 'banner'){//轮播
                $info = Db::name('banner')
                    ->where('position',2)
                    ->where('status',0)
                    ->where('delete',0)
                    ->order('id desc')
                    ->limit(4)
                    ->select();
            }
            if ($img == 'header'){//头部
                $info = Db::name('banner')
                    ->where('position',1)
                    ->where('status',0)
                    ->where('delete',0)
                    ->order('id desc')->find();
            }
            if ($img == 'information'){//行业资讯
                $info = Db::name('banner')
                    ->where('position',3)
                    ->where('status',0)
                    ->where('delete',0)
                    ->order('id desc')
                    ->limit(2)
                    ->select();
            }
            return json($info);
        }
        if ($type == 'tzgg'){//主页 -- 通知公告
            $tzgg = Db::name("i_notice")
                ->where(['delete'=>0,'state'=>1])
                ->limit(7)
                ->order("id desc")
                ->select();
            return Json($tzgg);
        }
        if ($type == 'sign'){//主页 -- 通知公告
            $phone = input('phone');
            $info = Db::name("sign")
                ->where('phone',$phone)->find();
            return Json($info);
        }
        if ($type == 'hyzx'){//主页 -- 行业资讯
            $hyzx = Db::name('i_industry')
                ->where(['delete'=>0,'state'=>1])
                ->select();
            return Json($hyzx);
        }
        if($type == 'title'){//主页 -- 搜索 --是否存在
            $title = input('title');
            $info = Db::name('bidding_hall')->whereLike('title',"%$title%")->select()->toArray();
            if (!empty($info)){
                $arr=[
                    'code'=>1,
                    'msg'=>'成功'
                ];
            }else{
                $arr=[
                    'code'=>2,
                    'msg'=>'暂无搜索的内容'
                ];
            }
            return $arr;
        }
        if ($type == 'zbdt'){//招标大厅
            $title = input('title');
            $cate=input('cate');
            $price = input('price');
            $bid = input('bid');
            $zbdt = Db::name('bidding_hall')
                ->field('b.id,time,number,title,price,times,describe,cate,file,b.state,b.name,phone,c.name as catename,i.name as catenamepid')
                ->alias('b')
                ->join(['i_category' => 'c'], 'b.cate=c.id')
                ->where('b.state',1)
                ->join(['i_category' => 'i'], 'b.catepid=i.id')
                ->whereLike('c.name',"%$cate%")
                ->whereLike('bid',"%$bid%")
                ->whereLike('title',"%$title%")
                ->order('id desc')
                ->select();
            if($price==0){
                $zbdt = Db::name('bidding_hall')
                    ->field('b.id,time,number,title,price,times,describe,cate,file,b.state,b.name,phone,c.name as catename,i.name as catenamepid')
                    ->alias('b')
                    ->join(['i_category'=>'c'],'b.cate=c.id')
                    ->join(['i_category'=>'i'],'b.catepid=i.id')
                    ->where('b.state',1)
                    ->whereLike('c.name',"%$cate%")
                    ->whereLike('bid',"%$bid%")
                    ->whereLike('title',"%$title%")
                    ->order('id desc')
                    ->select();
            }
            if ($price==1){
                $zbdt = Db::name('bidding_hall')
                    ->field('b.id,time,number,title,price,times,describe,cate,file,b.state,b.name,phone,c.name as catename,i.name as catenamepid')
                    ->alias('b')
                    ->join(['i_category'=>'c'],'b.cate=c.id')
                    ->join(['i_category'=>'i'],'b.catepid=i.id')
                    ->where("price","<",3000)
                    ->where('b.state',1)
                    ->whereLike('c.name',"%$cate%")
                    ->whereLike('bid',"%$bid%")
                    ->order('id desc')
                    ->select();
            }
            if ($price==2){
                $zbdt = Db::name('bidding_hall')
                    ->field('b.id,time,number,title,price,times,describe,cate,file,b.state,b.name,phone,c.name as catename,i.name as catenamepid')
                    ->alias('b')
                    ->join(['i_category'=>'c'],'b.cate=c.id')
                    ->join(['i_category'=>'i'],'b.catepid=i.id')
                    ->where("price","between",[3000,10000])
                    ->where('b.state',1)
                    ->whereLike('c.name',"%$cate%")
                    ->whereLike('bid',"%$bid%")
                    ->order('id desc')
                    ->select();
            }
            if ($price==3){
                $zbdt = Db::name('bidding_hall')
                    ->field('b.id,time,number,title,price,times,describe,cate,file,b.state,b.name,phone,c.name as catename,i.name as catenamepid')
                    ->alias('b')
                    ->join(['i_category'=>'c'],'b.cate=c.id')
                    ->join(['i_category'=>'i'],'b.catepid=i.id')
                    ->where("price","between",[10000,50000])
                    ->where('b.state',1)
                    ->whereLike('c.name',"%$cate%")
                    ->whereLike('bid',"%$bid%")
                    ->order('id desc')
                    ->select();
            }
            if ($price==4){
                $zbdt = Db::name('bidding_hall')
                    ->field('b.id,time,number,title,price,times,describe,cate,file,b.state,b.name,phone,c.name as catename,i.name as catenamepid')
                    ->alias('b')
                    ->join(['i_category'=>'c'],'b.cate=c.id')
                    ->join(['i_category'=>'i'],'b.catepid=i.id')
                    ->where("price",">",50000)
                    ->where('b.state',1)
                    ->whereLike('c.name',"%$cate%")
                    ->whereLike('bid',"%$bid%")
                    ->order('id desc')
                    ->select();
            }
            return Json($zbdt);
        }
        if ($type == 'zbdts'){//发布需求
            $timestamp = time();// -86400 秒数
            $days = 14;
            $date = strtotime("+".$days."day", $timestamp);
            $data = [
                'cate' =>input('cate'),
                'catepid'=>input('catepid'),
                'title'=>input('title'),
                'describe'=>input('describe'),
                'name'=>input('name'),
                'phone'=>input('phone'),
                'price'=>input('price'),
                'times'=>date('Y-m-d',$date),
                'file'=>input('file'),
                'fileTxt'=>input('fileTxt'),
                'day'=>$days+1
            ];
            $zbdts = Db::name('bidding_hall')->insert($data);
            if ($zbdts){
                $arr=[
                    'code'=>1,
                    'msg'=>'发布成功，请等待审核'
                ];
            }else{
                $arr=[
                    'code'=>0,
                    'msg'=>'发布失败，请重新输入'
                ];
            }
            return json($arr);
        }
        if($type == 'zbdtdetails'){//招标大厅详情
            $id = input('id');
            $info = Db::name('bidding_hall')
                ->field('b.id,b.time,b.title,b.number,b.price,b.times,b.describe,b.name,b.phone,b.bid,b.file,b.fileTxt,b.day,i.name catename,c.name catenamepid')
                ->alias('b')
                ->join('i_category i','b.cate=i.id')
                ->join('i_category c','b.catepid=c.id')
                ->where('b.id',$id)
                ->find();
            return json($info);
        }
        if ($type == 'tb'){//立即投标
            $data = [
                'pid'=>input('pid'),
                'price'=>input('price'),
                'other'=>input('other'),
                'name'=>input('name'),
                'phone'=>input('phone'),
            ];
            $infodata = Db::name('bidding_hall')->where('id',$data['pid'])->find();
            $number = [
                'id'=>$infodata['id'],
                'number'=>$infodata['number']+1
            ];
            Db::name('bidding_hall')->update($number);
            $info = Db::name('bid')->insert($data);
            if ($info){
                $arr=[
                    'code'=>1,
                    'msg'=>'投标成功'
                ];
            }else{
                $arr=[
                    'code'=>2,
                    'msg'=>'投标失败'
                ];
            }
            return json($arr);
        }
        if($type == 'classification'){//招标大厅--一级栏目
            $info = Db::name('i_category')->where('pid',0)->order('id asc')->select();
            return json($info);
        }
        if ($type == 'Deadline_days'){
            $info = Db::name('bidding_hall')->field('id,time,times,day')->where('delete',0)->select()->toArray();
            foreach ($info as $v){
                $v['timed'] = time();
                $v['times'] = strtotime($v['times']);
                $v['timeday'] = $v['times'] - $v['timed'];
                if($v['day'] > 0){
                    $v['day'] = intval(ceil($v['timeday']/86400))+1;
                }elseif($v['day'] <= 0){
                    $v['day'] = 0;
                }
                $data = [
                    'id'=>$v['id'],
                    'day'=>$v['day']
                ];
                Db::name('bidding_hall')->update($data);
                dump($v);
            }
        }
        if ($type == 'tbs'){//中标详情页--判断投标数量--最大是：10
            $id = input('id');
            $info = Db::name('bid')->where('pid',$id)->count();
            $infoday = Db::name('bidding_hall')->where('id',$id)->find();
            if ($info <= '10' && $infoday['day'] != 0){
                $arr=[
                    'code'=>1,
                    'msg'=>'立即投标'
                ];
            }else{
                //投标数量到10人后，禁止投标
                $dates = [
                    'id'=>$id,
                    'bid'=>1
                ];
                Db::name('bidding_hall')->update($dates);
                $arr=[
                    'code'=>2,
                    'msg'=>'已停止投标'
                ];
            }
            return json($arr);
        }
        if ($type == 'tbstate'){//投标详情页的中标状态
            $id = input('id');
            $phone = input('phone');
            $info = Db::name('bid')->where('pid',$id)->where('phone',$phone)->where('isdelete',0)->find();
            if (!empty($info)){
                $mark = '';
                if ($info['mark'] == 0){
                    $mark = '已投标等待雇主选标';
                }else if ($info['mark'] == 1 || $info['mark'] == 2 || $info['mark'] == 3){
                    $mark = '已中标';
                }else if ($info['mark'] == 4){
                    $mark = '未通过';
                }else if ($info['mark'] == 5){
                    $mark = '已完成';
                }
                $arr = [
                    'code'=>1,
                    'mark'=>$mark,
                ];
            }else{
                $arr = [
                    'code'=>2,
                ];
            }
            return json($arr);
        }
        if($type == 'password'){//账户设置--密码
            $data=[
                'phone'=>input('phone'),
                'poss'=>md5(input('poss'))
            ];
            $info = Db::name('sign')->where('phone',$data['phone'])->where('poss',$data['poss'])->find();
            if (!empty($info)){
                $arr=[
                    'code'=>1,
                    'msg'=>'密码正确'
                ];
            }else{
                $arr=[
                    'code'=>2,
                    'msg'=>'密码错误'
                ];
            }
            return json($arr);
        }
        if ($type == 'lmxz'){//导航 -- 类目选择
            $lmxz = Db::name('i_category')->where('pid',0)->select()->toArray();//一维数组
            foreach ($lmxz as &$v){
                $v['second']=Db::name('i_category')->where('pid',$v['id'])->select()->toArray();//二维数组
            }
            return Json($lmxz);
        }
        if($type == 'company'){//登录用户的公司名称
            $phone = input('phone');
            $info = Db::name('sign')->where('phone',$phone)->find();
            return json($info);
        }
        if ($type == 'setup'){//账户设置
            $phone = input('phone');
            $info = Db::name('sign')
                ->where('phone',$phone)
                ->find();
            return json($info);
        }
        if ($type == 'setupInsert'){//账户设置--保存
            $ruleForm = json_decode(input('ruleForm'),true);
            $info = Db::name('sign')->update($ruleForm);
            if ($info){
                $arr=[
                    'code'=>1,
                    'msg'=>'保存成功！'
                ];
            }else{
                $arr=[
                    'code'=>2,
                    'msg'=>'您未修改任何数据！'
                ];
            }
//      前端FormData传值的时候需要给要传的那个数组进行json编码，JSON.stringify(),然后后端需要使用json_decode()方法来对那个数组进行解码
            return Json($arr);
        }
        if($type == 'gzt'){//工作台--我的投标
            $work = input('work');
            if($work == 'remove'){
                $data = [
                    'id'=>input('id'),
                    'isdelete'=>input('isdelete')?0:1
                ];
                $info = Db::name('bid')->update($data);
                if ($info){
                    $arr=[
                        'code'=>1,
                        'msg'=>'删除成功！'
                    ];
                }else{
                    $arr=[
                        'code'=>2,
                        'msg'=>'删除失败！'
                    ];
                }
                return json($arr);
            }
            if ($work ==  'bid') {//查询--选标中
                $phone = input('phone');
                $gzt = Db::name('bidding_hall')
                    ->field('b.id,b.title,b.times,i.pid,i.phone phonebid,i.mark,i.choose,i.id pid,i.isdelete')
                    ->alias('b')
                    ->join('bid i', 'b.id=i.pid')
                    ->where('i.phone', $phone)
                    ->where('i.mark', 0)
                    ->where('isdelete',0)
                    ->select();
                return Json($gzt);
            }
            if ($work ==  'sign') {//查询--待签约
                $phone = input('phone');
                $gzt = Db::name('bidding_hall')
                    ->field('b.id,b.title,b.times,i.pid,i.phone phonebid,i.mark,i.choose,i.id pid,i.isdelete')
                    ->alias('b')
                    ->join('bid i', 'b.id=i.pid')
                    ->where('i.phone', $phone)
                    ->where('i.mark', 1)
                    ->where('isdelete',0)
                    ->select();
                return Json($gzt);
            }
            if ($work ==  'implements') {//查询--执行中
                $phone = input('phone');
                $gzt = Db::name('bidding_hall')
                    ->field('b.id,b.title,b.times,i.pid,i.phone phonebid,i.mark,i.choose,i.id pid,i.isdelete')
                    ->alias('b')
                    ->join('bid i', 'b.id=i.pid')
                    ->where('i.phone', $phone)
                    ->where('i.mark', 2)
                    ->where('isdelete',0)
                    ->select();
                return Json($gzt);
            }
            if ($work ==  'accepteds') {//查询--待验收
                $phone = input('phone');
                $gzt = Db::name('bidding_hall')
                    ->field('b.id,b.title,b.times,i.pid,i.phone phonebid,i.mark,i.choose,i.id pid,i.isdelete')
                    ->alias('b')
                    ->join('bid i', 'b.id=i.pid')
                    ->where('i.phone', $phone)
                    ->where('i.mark', 3)
                    ->where('isdelete',0)
                    ->select();
                return Json($gzt);
            }
            if ($work ==  'failed') {//查询--未通过
                $phone = input('phone');
                $gzt = Db::name('bidding_hall')
                    ->field('b.id,b.title,b.times,i.pid,i.phone phonebid,i.mark,i.choose,i.id pid,i.isdelete')
                    ->alias('b')
                    ->join('bid i', 'b.id=i.pid')
                    ->where('i.phone', $phone)
                    ->where('i.mark', 4)
                    ->where('isdelete',0)
                    ->select();
                return Json($gzt);
            }
            if ($work ==  'completeds') {//查询--已完成
                $phone = input('phone');
                $gzt = Db::name('bidding_hall')
                    ->field('b.id,b.title,b.times,i.pid,i.phone phonebid,i.mark,i.choose,i.id pid,i.isdelete')
                    ->alias('b')
                    ->join('bid i', 'b.id=i.pid')
                    ->where('i.phone', $phone)
                    ->where('i.mark', 5)
                    ->where('isdelete',0)
                    ->select();
                return Json($gzt);
            }
            if ($work == 'Bidselection'){//修改--待签约
                $data = [
                    'id'=>input('id'),
                    'choose'=>input('choose'),
                    'mark'=>input('mark')
                ];
                $info = Db::name('bid')->update($data);
                if ($info){
                    $arr=[
                        'code'=>1,
                        'msg'=>'选标成功！待签约'
                    ];
                }else{
                    $arr=[
                        'code'=>2,
                        'msg'=>'选标失败！'
                    ];
                }
                return json($arr);
            }
            if ($work == 'implement'){//修改--执行中
                $data = [
                    'id'=>input('id'),
                    'mark'=>input('mark')
                ];
                $info = Db::name('bid')->update($data);
                if ($info){
                    $arr=[
                        'code'=>1,
                        'msg'=>'修改成功！执行中'
                    ];
                }else{
                    $arr=[
                        'code'=>2,
                        'msg'=>'修改失败！'
                    ];
                }
                return json($arr);
            }
            if ($work == 'accepted'){//修改--待验收
                $data = [
                    'id'=>input('id'),
                    'mark'=>input('mark')
                ];
                $info = Db::name('bid')->update($data);
                if ($info){
                    $arr=[
                        'code'=>1,
                        'msg'=>'修改成功！待验收'
                    ];
                }else{
                    $arr=[
                        'code'=>2,
                        'msg'=>'修改失败！'
                    ];
                }
                return json($arr);
            }
            if ($work == 'completed'){//修改--已完成||未通过
                $data = [
                    'id'=>input('id'),
                    'mark'=>input('mark')
                ];
                $info = Db::name('bid')->update($data);
                if ($info){
                    if ($data['mark'] == '5'){
                        $arr=[
                            'code'=>1,
                            'msg'=>'修改成功！已完成'
                        ];
                    }
                    if ($data['mark'] == '4'){
                        $arr=[
                            'code'=>1,
                            'msg'=>'修改成功！未通过'
                        ];
                    }
                }else{
                    $arr=[
                        'code'=>2,
                        'msg'=>'修改失败！'
                    ];
                }
                return json($arr);
            }
        }
    }
    public function logins(){
        $sub = input('sub');
        if ($sub == 'sign'){//登录
            $data=[
                'phone'=>input('phone'),
                'poss'=>md5(input('poss')),
            ];
            $info = Db::name('sign')->where('phone',$data['phone'])->select()->toArray();
            if (!empty($info)){
                $infos = Db::name('sign')->where(['phone'=>$data['phone'],'poss'=>$data['poss']])->select()->toArray();
                if (!empty($infos)){
                    $arr=[
                      'code'=>0,
                      'msg'=>'恭喜你,登录成功',
                    ];
                }else{
                    $arr=[
                        'code'=>1,
                        'msg'=>'抱歉哦！密码错误',
                    ];
                }
            }else{
                $arr=[
                    'code'=>2,
                    'msg'=>'用户名不存在哦！请注册',
                ];
            }
            return Json($arr);
        }
        if($sub == 'regist'){//注册
            $data=[
                'phone'=>input('phone'),
                'poss'=>md5(input('poss')),
                'company'=>input('company'),
                'credit'=>input('credit'),
                'name'=>input('name'),
                'email'=>input('email')
            ];
            $datas = Db::name('sign')->where('phone',$data['phone'])->select()->toArray();
            if (!empty($datas)){
                $arr=[
                    'code'=>0,
                    'msg'=>'用户名已存在'
                ];
                return Json($arr);
            }else{
                $info=Db::name('sign')->insert($data);
                if ($info!==false){
                    $arr=[
                        'code'=>1,
                        'msg'=>'恭喜你，注册成功'
                    ];
                }else{
                    $arr=[
                        'code'=>2,
                        'msg'=>'抱歉哦，注册失败'
                    ];
                }
                return Json($arr);
            }
        }
    }
}